#!/usr/bin/python3

import os
import tarfile
import zipfile
# from py7zr import SevenZipFile
import build_utils
import subprocess

def extract_file(file_path, extract_to):
    """根据文件扩展名解压文件到指定目录"""
    if file_path.endswith('.tar.gz') or file_path.endswith('.tgz'):
        with tarfile.open(file_path, 'r:gz') as tar:
            tar.extractall(path=extract_to)
    elif file_path.endswith('.tar.xz'):
        with tarfile.open(file_path, 'r:xz') as tar:
            tar.extractall(path=extract_to)
    elif file_path.endswith('.tar.bz2'):
        with tarfile.open(file_path, 'r:bz2') as tar:
            tar.extractall(path=extract_to)
    elif file_path.endswith('.zip'):
        with zipfile.ZipFile(file_path, 'r') as zip_ref:
            zip_ref.extractall(extract_to)
    # elif file_path.endswith('.7z'):
    #     with SevenZipFile(file_path, 'r') as seven_zip:
    #         seven_zip.extractall(extract_to)
    else:
        print(f"Unsupported file format: {file_path}")

def extract_all_in_dir(dir_path, extract_to):
    """遍历目录，解压所有支持的压缩文件到指定目录"""
    for root, dirs, files in os.walk(dir_path):
        for file in files:
            print(f'extract file: {file}')
            if file.endswith(('.tar.gz', '.tgz', '.tar.xz', '.tar.bz2', '.zip', '.7z')):
                file_path = os.path.join(root, file)
                print(f"Extracting {file_path}...")
                if not os.path.exists(extract_to):
                    extract_file(file_path, extract_to)

def print_install_memtion(name, cmd):
    print(f'install {name}, shell command: \'{cmd}\'')
    process = subprocess.Popen(
        cmd,
        shell=True,
        stdout=subprocess.PIPE
    )
    while True:
        line = process.stdout.readline()
        if not line:
            break
        print(line.decode().strip())

if __name__ == "__main__":
    script_path = os.path.abspath(__file__)
    curdir = os.path.dirname(script_path)
    source_dir = curdir + '/buildtools/'  # 源目录，包含压缩文件
    destination_dir = curdir + '/toolchains/'  # 目标目录，解压文件将放在这里
    extract_all_in_dir(source_dir, destination_dir)
    # print_install_memtion('nix-shell', 'sh <(curl -L https://nixos.org/nix/install) --no-daemon')
    print_install_memtion('aclocal', 'sudo apt-get install automake')
    print_install_memtion('libtool', 'sudo apt-get install libtool')
    print_install_memtion('m4', 'sudo apt-get install m4')
    print_install_memtion('cmake', 'sudo apt-get install cmake')
    print_install_memtion('bazel', 'sudo apt-get install bazel')
    print_install_memtion('protobuf', 'sudo pip install protobuf')
    print_install_memtion('PkgConfig', 'sudo apt install pkg-conf')
    print_install_memtion("protoc", 'sudo pip install grpcio grpcio-tools')
    print_install_memtion("protoc", 'sudo apt install protobuf-compiler libprotobuf-dev')
    print_install_memtion("mingw-w64", "sudo apt-get install mingw-w64")
    # sudo apt install qt6-tools-dev qt6-tools-dev-tools
    # https://nchc.dl.sourceforge.net/project/mingw-w64/mingw-w64/mingw-w64-release/mingw-w64-v11.0.0.zip?viasf=1
    # http://launchpadlibrarian.net/694408304/g++-mingw-w64_13.2.0-6ubuntu1+26.1_all.deb
    # http://launchpadlibrarian.net/725844309/mingw-w64_11.0.1-3build1_all.deb
    # https://launchpad.net/ubuntu/+source/mingw-w64/12.0.0-3/+build/28692960/+files/mingw-w64-common_12.0.0-3_all.deb
    # https://launchpad.net/ubuntu/+source/mingw-w64/12.0.0-3/+build/28692960/+files/mingw-w64-i686-dev_12.0.0-3_all.deb
    # curl -L -o buildtools/mingw-w64-x86-64-dev_12.0.0-3_all.deb  https://launchpadlibrarian.net/743775681/mingw-w64-x86-64-dev_12.0.0-3_all.deb
#     export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static
# export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup
    print_install_memtion("tree-sitter-cli", "cargo install tree-sitter-cli --locked")
